﻿Imports System.Net
Imports HTLibrary
Imports TNCBAL
Imports TNCDAL

Public Class ucCompany
    'Private objCompanyRepo As New CompanyRepository
    Private _objCompanyController As New CompanyController
    Private _objCurrCompany As tblCompany
    Private _objCustomerControl As New ucCustomer()

    Public Sub New()
        InitializeComponent()

        TextBoxHelper.TextBox_InitUpperStringEvent(Me.Controls, New List(Of String)({"txtCompanyName", "txtAddress"}))
        TextBoxHelper.TextBox_InitNonAlphabetCharEvent(Me.Controls, New List(Of String)({"txtTel", "txtFax"}))
        DataGridViewHelper.DataGridView_InitEvent(gridView)

    End Sub

    Private Sub ucCompany_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        InitCustomerControl()

        BindDataGridView()
        FormatDataGridView()
        InitCommands()
        'BarSearch.CloseSingleTab = True
    End Sub

    Public Sub InitCustomerControl()
        _objCustomerControl.AutoScroll = True
        _objCustomerControl.AutoScroll = True
        _objCustomerControl.Dock = System.Windows.Forms.DockStyle.Fill
        _objCustomerControl.Name = "objCustomerControl"
        TabControlPanel2.Controls.Add(Me._objCustomerControl)
    End Sub

    Public Sub FormatDataGridView()
        Dim hideColumns As New List(Of String)({"Id_Company", "IsActive"})
        Dim frozenColumnName = "Name"

        CViewer.FormatDataGridView(gridView, _
                                   hideColumns, _
                                   Nothing, _
                                   frozenColumnName)
    End Sub

    Public Sub BindDataGridView(ByVal columnName As String, ByVal someText As Integer)
        Dim query As IQueryable(Of tblCompany) = _objCompanyController.SelectCustom(txtCompanyNameSearch.Text)
        Dim source As New BindingSource
        source.DataSource = query
        gridView.DataSource = source
        BindingNavigator1.BindingSource = source

        Dim indexRow As Integer = CViewer.GetIndexRowInDataGridViewByTextSearch(gridView, columnName, someText)
        If indexRow >= 0 Then
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next

        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)
    End Sub

    Public Sub BindDataGridView(Optional ByVal indexRow As Integer = -1)
        Dim query As IQueryable(Of tblCompany) = _objCompanyController.SelectCustom(txtCompanyNameSearch.Text)
        Dim source As New BindingSource
        source.DataSource = query
        gridView.DataSource = source
        BindingNavigator1.BindingSource = source

        If indexRow >= 0 Then
            'gridViewCompany.FirstDisplayedScrollingRowIndex = indexRow
            'Set current row
            'gridViewCompany.Rows(indexRow).Selected = True
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next

        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)
    End Sub

    Public Sub LoadForm()
        'show result
        txtCompanyName.Text = _objCurrCompany.Name
        txtAddress.Text = _objCurrCompany.Address
        txtFax.Text = _objCurrCompany.Fax
        txtTel.Text = _objCurrCompany.Tel

        'If _objCurrCompany.IsExport = 0 Then
        '    rbtnImport.Checked = True
        'ElseIf _objCurrCompany.IsExport = 1 Then
        '    rbtnExport.Checked = True
        'Else
        '    rbtnBoth.Checked = True
        'End If
    End Sub

    Public Sub GetInfoByForm()
        With _objCurrCompany
            'If rbtnBoth.Checked Then
            '    .IsExport = 2
            'ElseIf rbtnExport.Checked Then
            '    .IsExport = 1
            'Else
            '    .IsExport = 0
            'End If
            '.IsExport = 2
            .Name = txtCompanyName.Text
            .Address = txtAddress.Text
            .Fax = txtFax.Text
            .Tel = txtTel.Text
        End With
    End Sub

    Public Sub ResetControls()
        CViewer.ResetControls(Me.Controls)
        '_ucCommands.EnableButtons(False, gridView.Rows.Count) 'disable 2 nút edit và delete

        'Init obj
        _objCurrCompany = New tblCompany
        _objCurrCompany.IsActive = True
        'rbtnBoth.Checked = True
    End Sub

#Region "Commands"
    ''' <summary>
    ''' Init commands
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitCommands()
        Dim controlCollect As New List(Of Control)
        controlCollect.Add(BarSearch)
        '_ucCommands = New ucCommands(Me, controlCollect)
        _ucCommands.InitControl(Me, controlCollect)
        _ucCommands.ShowHideButtons(True, True, True)
        _ucCommands.btnAddEvent_Click = New EventHandler(AddressOf btnAdd_Click)
        _ucCommands.btnEditEvent_Click = New EventHandler(AddressOf btnEdit_Click)
        _ucCommands.btnDeleteEvent_Click = New EventHandler(AddressOf btnDel_Click)
        _ucCommands.btnUpdateEvent_Click = New EventHandler(AddressOf btnUpdate_Click)
        _ucCommands.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel_Click)
        _ucCommands.Dock = DockStyle.Fill
        PanelExCommand.Controls.Add(_ucCommands)
    End Sub

    Public Sub FocusControl()
        txtCompanyName.Focus()
        txtCompanyName.SelectionLength = 0
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(True)
        ResetControls()
        FocusControl()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        FocusControl()
        'EnableButtons(True)
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If MessageBox.Show("Delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Try
                Dim indexRow As Integer = gridView.CurrentRow.Index
                _objCurrCompany.IsActive = False
                _objCompanyController.Update(_objCurrCompany)

                'Xóa row tại indexRow và focus sau khi xóa
                gridView.Rows.RemoveAt(indexRow)
                indexRow -= 1
                If indexRow >= 0 Then
                    For Each col As DataGridViewColumn In gridView.Columns
                        If col.Visible Then
                            gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                            Exit For
                        End If
                    Next
                End If

                'Write log
                Dim objLogController As New LogController
                objLogController.Insert(enumAction.Delete, String.Format("Company Name {0}", _objCurrCompany.Name))

                'BindDataGridView(indexRow)
                'gridViewCompany.Rows.Remove(gridViewCompany.CurrentRow)
                'If gridViewCompany.Rows.Count = 0 Then
                '    ResetControls()
                'End If
            Catch ex As Exception
#If DEBUG Then
                Throw ex
#Else
                MessageBox.Show(ex.Message)
#End If
            End Try

        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            GetInfoByForm()

            Dim action As enumAction
            'Dim indexRow As Integer = -1
            If _objCurrCompany.ID_Company > 0 Then
                _objCompanyController.Update(_objCurrCompany)
                action = enumAction.Edit
                'indexRow = gridView.CurrentRow.Index
            Else
                _objCompanyController.Insert(_objCurrCompany)
                action = enumAction.Add
                'indexRow = gridView.Rows.Count
            End If
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(action, String.Format("Company ({0})", _objCurrCompany.Name))
            'Refresh gridview
            BindDataGridView("ID_Company", _objCurrCompany.ID_Company)
        Catch ex As Exception
#If DEBUG Then
            Throw ex
#Else
            MessageBox.Show(ex.Message)
#End If
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(False)
        gridViewCompany_CurrentCellChanged(Nothing, Nothing)
    End Sub
#End Region


    Private Sub gridViewCompany_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridView.CurrentCellChanged
        'Load info
        Try
            If _ucCommands Is Nothing Then
                Return
            End If

            If gridView.CurrentRow Is Nothing Then
                Return
            End If

            'Kiểm tra nếu đang cập nhật/thêm mới thì không hiển thị dữ liệu
            If _ucCommands.btnUpdate.Enabled Then
                Return
            End If


            Dim id As Integer = gridView.CurrentRow.Cells("ID_Company").Value
            _objCurrCompany = _objCompanyController.SelectRecordById(id)
            'load customer
            _objCustomerControl._objCurrCompany = _objCurrCompany
            _objCustomerControl.BindDataGridView()

            'Fill company's fields
            LoadForm()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub TabControl1_SelectedTabChanged(ByVal sender As System.Object, ByVal e As DevComponents.DotNetBar.TabStripTabChangedEventArgs) Handles TabControl1.SelectedTabChanged
        If _ucCommands IsNot Nothing Then
            _ucCommands.btnCancel.PerformClick()
        End If

    End Sub

#Region "Search Controls"
    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindDataGridView(-1)
    End Sub


    Private Sub btnCancelSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelSearch.Click
        txtCompanyNameSearch.Text = ""
        Me.btnSearch.PerformClick()
    End Sub
#End Region

End Class
